# -*- coding: utf-8 -*-
from accuracy import RMSE, MAE, MAPE, R_square
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from model import *
from read_data import *
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import time
from timeit import default_timer as timer
"""
Created on  2020
@author: yyli18@lzu.edu.cn
"""
import warnings
warnings.filterwarnings("ignore")
# from ALO_NEW import *

warnings.filterwarnings("ignore")
# In[158]:


def preplot(y_test_pre, y_test_rel, figpath):
    # 预测图
    plt.plot(y_test_pre, color='red', label='prediction')
    plt.plot(y_test_rel, color='blue', label='y_test')
    plt.xlabel('No. of Trading Hours')
    plt.ylabel('Close Value (scaled)')
    plt.legend(loc='upper left')
    fig = plt.gcf()
    fig.set_size_inches(15, 5)
    fig.savefig(figpath, dpi=300)
    plt.show()
# In[158]:


def run(city, mod, sequence_length, horizon, decomposition):
    times = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
    if decomposition in mod:
     #   "IMF1","IMF2","IMF3","IMF4","IMF5","IMF6","IMF7","IMF8","IMF9","IMF10"
        # a = ["IMF1","IMF2","IMF3","IMF4","IMF5","IMF6","IMF7","IMF8","IMF9","IMF10","IMF11"]
        # a = ['0',  '1', '2',  '3',
        #      '4',  '5']
        a = ['0',  '1', '2',  '3',
             '4',  '5', '6', '7', '8', '9', '10']
        # a = [
        #     'imf0', 'imf1',
        #     'imf2', 'imf3',
        #     'imf4', 'imf5',
        #     'imf6'
        # ]
        filename = str(times)+'_' + "h"+str(horizon)+"_"+mod + ".csv"
        figname = str(times)+'_' + "h"+str(horizon)+"_"+mod+".png"
        savepath = save_path+city+"/"+mod + "/"
        generpath(savepath)
        datapath = data_path + 'data'+"_" + decomposition + ".csv"
        for i in a:
            index = saveindex = i
            data = rdata(datapath)
            data = data[index]
            x_train_initial, x_test_initial, y_train_initial, y_test_initial = splitdata(
                data, sequence_length, horizon)
            x_train, x_test, y_train, y_test = standata(
                x_train_initial, x_test_initial, y_train_initial, y_test_initial)

            # SVR可用
            # x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1]))
            # x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1]))
            # model = SVR_model(x_train,y_train)

            # model = BPNN_model(x_train,y_train,sequence_length,epochs,verbose)
            model = LSTM_model(
                x_train, y_train, sequence_length, n_multi, epochs, verbose)
            pre = model.predict(x_test)
            y_test_rel, y_test_pre = iverse_data(y_train_initial, pre, y_test)

            generfile(savepath, filename, len(y_test))
            datasave(savepath+filename, saveindex, y_test_pre)
            print("----------", index, "had finished", "----------")
            print('MAE：', MAE(y_test_rel, y_test_pre))
            print('RMSE：', RMSE(y_test_rel, y_test_pre))
            print('MAPE：', MAPE(y_test_rel, y_test_pre)[0])
            print('R方：', R_square(y_test_rel, y_test_pre))

        datapr = pd.read_csv(savepath+filename)
        datapr.fillna(method='pad', inplace=True)
        datapr1 = np.array(datapr)
        y_pre = np.sum(datapr1[:, 2:], axis=1)
        y_pre = y_pre.reshape(-1, 1)
        print(y_pre[-10:])
        datare = pd.read_csv(data_path+origin_data)
        datare.fillna(method='pad', inplace=True)
        y_rel = np.array(datare[city][-len(y_pre):]).reshape(-1, 1)
        print(y_rel[-10:])
        y_pre = np.array(y_pre).reshape(len(y_pre),)
        y_rel = np.array(y_rel).reshape(len(y_pre),)

        preplot(y_pre, y_rel, savepath+figname)

        mae = MAE(y_rel, y_pre)
        rmse = RMSE(y_rel, y_pre)
        mape = MAPE(y_rel, y_pre)
        R = R_square(y_rel, y_pre)
        lstm_zb = [mae, rmse, mape, R]
        lstm_zb = np.array(lstm_zb).reshape(-1, 1)
        zbfile = "合并后指标" + ".csv"
        generfile(savepath, zbfile, len(lstm_zb))
        datasave(savepath + zbfile, "index", lstm_zb)
        print("MAE:", mae)
        print("RMSE:", rmse)
        print("MAPE", mape)
        print("R方：", R)

        generfile(savepath, str(times)+'_' + "合并结果.csv", len(y_test))
        datasave(savepath+str(times)+'_' + "合并结果.csv",
                 mod+"_h"+str(horizon), y_pre)


# In[153]:
data_path = ""
save_path = "预测/"
origin_data = "data.csv"
n_multi = 0
verbose = 0
sequence_length = 4
# 预测长度
netmodel = "LSTM"
decomposition = 'CEEMDAN'
mod = netmodel + '_' + decomposition
cityindx = ["Power"]
epochs_index = [30]
hindex = [1]
# """
# In[153]:
for city in cityindx:
    for h in hindex:
        for epo in epochs_index:
            epochs = epo
            horizon = h
            city = city
            print("----------", city, mod, "h:", horizon,
                  "epochs:", epochs, "----------")
            run(city, mod, sequence_length, horizon, decomposition)

# """
